<template>
  <div class="sysuser-container">
    <h1>管理员管理</h1>
    <div class="operation-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入名称或电话关键词搜索"
        style="width: 300px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAdd">新增管理员</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 15px;"
    >
      <el-table-column prop="userId" label="ID" width="80" />
      <el-table-column prop="sysName" label="工作人员名称" />
      <el-table-column prop="sysAddress" label="工作人员地址" />
      <el-table-column prop="sysPhone" label="工作人员电话" />
      <el-table-column prop="sysEmail" label="工作人员邮箱" />
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="roleName" label="所属角色" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.userId)">删除</el-button>
          <el-button type="info" size="small" @click="showAddLoginDialog(scope.row)">分配账号</el-button>
          <el-button type="warning" size="small" @click="showAssignRoleDialog(scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <div class="pagination-bar" v-if="total > 0">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      />
    </div>

    <!-- 分配账号弹窗 -->
    <el-dialog title="为管理员添加登录账号" v-model="loginDialogVisible" width="500px">
      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        label-width="120px"
      >
        <el-form-item label="工作人员id" disabled>
          <el-input v-model="loginForm.sysUserId" />
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="loginForm.account" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入登录密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="loginDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitLoginInfo">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog title="为管理员分配角色" v-model="roleDialogVisible" width="500px">
      <el-form
        :model="roleForm"
        ref="roleFormRef"
        label-width="120px"
      >
        <el-form-item label="管理员名称" disabled>
          <el-input v-model="roleForm.userName" />
        </el-form-item>
        <el-form-item label="选择角色" prop="roleId" :rules="{ required: true, message: '请选择角色', trigger: 'change' }">
          <el-select v-model="roleForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRoleAssignment">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="formData"
        ref="formRef"
        label-width="120px"
      >
        <el-form-item label="工作人员名称" prop="sysName" :rules="{ required: true, message: '请输入工作人员名称', trigger: 'blur' }">
          <el-input v-model="formData.sysName" placeholder="请输入工作人员名称" />
        </el-form-item>
        <el-form-item label="工作人员地址" prop="sysAddress" :rules="{ required: true, message: '请输入工作人员地址', trigger: 'blur' }">
          <el-input v-model="formData.sysAddress" placeholder="请输入工作人员地址" />
        </el-form-item>
        <el-form-item label="工作人员电话" prop="sysPhone" :rules="{ required: true, message: '请输入工作人员电话', trigger: 'blur' }">
          <el-input v-model="formData.sysPhone" placeholder="请输入工作人员电话" />
        </el-form-item>
        <el-form-item label="工作人员邮箱" prop="sysEmail" :rules="{ required: true, message: '请输入工作人员邮箱', trigger: 'blur', type: 'email', message: '请输入正确的邮箱格式' }">
          <el-input v-model="formData.sysEmail" placeholder="请输入工作人员邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessageBox } from 'element-plus'
import {
  getsysuserPageAPI,
  addsysuserAPI,
  updatesysuserAPI,
  deletesysuserAPI,
  searchsysuserAPI,
  addLoginInfoAPI
} from '@/apis/sysuserAPI';
import { getRoleListAPI, assignRole,getUserRolesAPI } from '@/apis/sysAPI'; // 请替换为实际的API文件路径

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');

// 角色相关数据
const roleList = ref([]);
const roleDialogVisible = ref(false);
const roleFormRef = ref(null);
const roleForm = reactive({
  userId: null,
  userName: '',
  roleId: null
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增管理员');
const formRef = ref(null);
const formData = reactive({
  userId: null,
  sysName: '',
  sysAddress: '',
  sysPhone: '',
  sysEmail: ''
});

// 登录账号弹窗相关
const loginDialogVisible = ref(false);
const loginFormRef = ref(null);
const loginForm = reactive({
  sysUserId: null,
  account: '',
  password: ''
});

const loginRules = {
  account: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
};

// 初始化页面加载数据
onMounted(() => {
  fetchSysuserList();
  fetchRoleList();
});

// 获取管理员列表
const fetchSysuserList = async () => {
  try {
    const response = await getsysuserPageAPI(currentPage.value);
    console.log(response);

    if (response.code === 0) {
      const users = response.data.records;
      // 为每个用户获取角色信息
      for (const user of users) {
        await fetchUserRole(user);
      }
      tableData.value = users;
      total.value = response.data.total;
      pageSize.value = response.data.size;
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error);
    ElMessage.error('获取管理员列表失败');
  }
};

// 获取用户角色信息
const fetchUserRole = async (user) => {
  try {
    const response = await getUserRolesAPI({ userId: user.userId });
    if (response.code === 0) {
      user.roleName = response.data || '未分配';
    } else {
      user.roleName = '未分配';
    }
  } catch (error) {
    console.error(`获取用户${user.userId}角色失败:`, error);
    user.roleName = '获取失败';
  }
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleListAPI();
    if (response.code === 0) {
      roleList.value = response.data;
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    fetchSysuserList();
    return;
  }

  try {
    const response = await searchsysuserAPI(searchKeyword.value);
    if (response.code === 0) {
      const users = response.data;
      // 为搜索到的用户获取角色信息
      for (const user of users) {
        await fetchUserRole(user);
      }
      tableData.value = users;
      total.value = response.data.length;
    }
  } catch (error) {
    console.error('搜索管理员失败:', error);
    ElMessage.error('搜索管理员失败');
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchSysuserList();
};

// 新增管理员
const handleAdd = () => {
  dialogTitle.value = '新增管理员';
  formData.userId = null;
  formData.sysName = '';
  formData.sysAddress = '';
  formData.sysPhone = '';
  formData.sysEmail = '';
  dialogVisible.value = true;
};

// 编辑管理员
const handleEdit = (row) => {
  dialogTitle.value = '编辑管理员';
  formData.userId = row.userId;
  formData.sysName = row.sysName;
  formData.sysAddress = row.sysAddress;
  formData.sysPhone = row.sysPhone;
  formData.sysEmail = row.sysEmail;
  dialogVisible.value = true;
};

// 提交表单（新增/编辑）
const handleSubmit = async () => {
  const form = formRef.value;
  if (!form) return;

  try {
    await form.validate();

    if (formData.userId) {
      const response = await updatesysuserAPI(formData);
      if (response.code === 0) {
        dialogVisible.value = false;
        fetchSysuserList();
        ElMessage.success('修改管理员成功');
      }
    } else {
      const response = await addsysuserAPI(formData);
      if (response.code === 0) {
        dialogVisible.value = false;
        fetchSysuserList();
        ElMessage.success('新增管理员成功');
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  }
};

// 显示分配账号弹窗
const showAddLoginDialog = (row) => {
  loginForm.sysUserId = row.userId;
  loginForm.account = '';
  loginForm.password = '';
  loginDialogVisible.value = true;
};

// 提交登录账号信息
const submitLoginInfo = async () => {
  console.log("提交的参数:", loginForm);

  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();

    const requestData = {
      sysUserId: Number(loginForm.sysUserId),
      account: loginForm.account.trim(),
      password: loginForm.password.trim()
    };

    const response = await addLoginInfoAPI(requestData);
    console.log("接口响应:", response);

    if (response.code === 0) {
      ElMessage.success('登录账号创建成功');
      loginDialogVisible.value = false;
    } else {
      ElMessage.error(response.msg || '登录账号创建失败');
    }
  } catch (error) {
    console.error('提交登录账号失败:', error);
    ElMessage.error('提交失败，请重试');
  }
};

// 显示分配角色弹窗
const showAssignRoleDialog = (row) => {
  roleForm.userId = row.userId;
  roleForm.userName = row.sysName;
  roleForm.roleId = null;

  // 尝试获取用户当前角色并选中
  const currentUser = tableData.value.find(u => u.userId === row.userId);
  if (currentUser && currentUser.roleName) {
    const currentRole = roleList.value.find(r => r.roleName === currentUser.roleName);
    if (currentRole) {
      roleForm.roleId = currentRole.id;
    }
  }

  roleDialogVisible.value = true;
};

// 提交角色分配
const submitRoleAssignment = async () => {
  if (!roleFormRef.value) return;

  try {
    await roleFormRef.value.validate();

    const requestData = {
      userId: roleForm.userId,
      roleId: roleForm.roleId
    };

    const response = await assignRole(requestData);
    if (response.code === 0) {
      ElMessage.success('角色分配成功');
      roleDialogVisible.value = false;
      fetchSysuserList(); // 刷新列表显示最新角色信息
    } else {
      ElMessage.error(response.msg || '角色分配失败');
    }
  } catch (error) {
    console.error('角色分配失败:', error);
    ElMessage.error('角色分配失败，请重试');
  }
};

// 删除管理员
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条管理员数据吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await deletesysuserAPI(id);
    if (response.code === 0) {
      ElMessage.success('删除管理员成功');
      fetchSysuserList();
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除管理员失败:', error);
      ElMessage.error('删除管理员失败');
    }
  }
};

// 引入Element组件
const { proxy } = getCurrentInstance();
const ElMessage = proxy.$message;
</script>

<style lang="scss" scoped>
.sysuser-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.operation-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.pagination-bar {
  margin-top: 15px;
  text-align: right;
}
</style>
